package com.atwulidun.config;

import com.atwulidun.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.ArrayList;
import java.util.List;

// 授权服务器
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    // 特别注意：这里是客户端，认证服务器和资源服务器三者集成到了一个服务器中
    // 一、授权码模式：authorizedGrantTypes("authorization_code")
    // 1.在客户端向认证服务器发请求，提示要用用户名和密码登录认证服务器
    // http://localhost:8080/oauth/authorize?client_id=admin&response_type=code
    // 2.用户给客户端授权，认证服务器给客户端发送一个授权码
    // 3.客户端通过该授权码向认证服务器换取一个accessToken(客户端无需知道认证服务器的密码)
    // http://localhost:8080/oauth/token?code=g5KFXZ&grant_type=authorization_code&redirect_uri=http://www.baidu.com&scope=all&client_id=admin&client_secret=112233
    // 或者不传client_id=admin&client_secret=112233，在Authorization->Basic Auth->username admin，password 112233
    // 4.客户端可通过accessToken访问资源服务器的内容
    // 二、密码模式：authorizedGrantTypes("password")
    // 1.用户直接把认证服务器的用户名和密码给到客户端，客户端通过该密码拿到AccessToken
    // http://localhost:8080/oauth/token?grant_type=password&scope=all&username=admin&password=123456
    // 2.最最容易漏的就是要在Authorization—>Basic Auth->username=client_id password=client_secret
    // 三、刷新令牌模式：authorizedGrantTypes("refresh_token")
    // 1.http://localhost:8080/oauth/token?grant_type=refresh_token&refresh_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbImFsbCJdLCJhdGkiOiI5ZTdiNDUyNi03ZTBiLTQyZWUtOWM5Ni1iNWQxNTJjOTJhODciLCJleHAiOjE2MTk2NjgzNDcsImF1dGhvcml0aWVzIjpbImFkbWluIl0sImp0aSI6IjQzZDRiODVmLTQxMzYtNDdhZC1iOGI3LTdmMTMyOGNiODBjZCIsImNsaWVudF9pZCI6ImFkbWluIn0.q9gYS4eIJ1qeviyC389MGU92lZAhitkwY8aTStPGzMY
    // 2.Authorization—>Basic Auth->username=client_id password=client_secret
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                // 配置client-id
                .withClient("admin")
                // 配置client-secret
                .secret(passwordEncoder.encode("112233"))
                // 配置访问token的有效期
                .accessTokenValiditySeconds(3600)
                // 配置刷新token的有效期
                .refreshTokenValiditySeconds(86400)
                // 自动授权配置，不需要每次手动点authorize
//                .autoApprove(true)
                // 配置redirect_uri，用于授权成功后跳转
//                .redirectUris("http://www.baidu.com")
                // 单点登陆时用下面这个，为oauth2client01demo的登录页面地址，授权成功后跳转
                .redirectUris("http://localhost:8081/login")
                // 配置申请权限范围
                .scopes("all")
                // 配置grant_type，表示授权类型
                .authorizedGrantTypes("authorization_code", "password", "refresh_token");
    }


    // 将token存储到Redis中
//    @Autowired
//    @Qualifier("redisTokenStore")
//    private TokenStore tokenStore;

    // 整合JWT
    @Autowired
    @Qualifier("jwtTokenStore")
    private TokenStore tokenStore;
    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    // 引入JWT内容增强器
    @Autowired
    private JwtTokenEnhancer jwtTokenEnhancer;



    @Autowired
    private UserService userService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 配置JWT内容增强器
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> delegates = new ArrayList<>();
        delegates.add(jwtTokenEnhancer);
        delegates.add(jwtAccessTokenConverter);
        enhancerChain.setTokenEnhancers(delegates);


        endpoints
                // 自定义登录逻辑
                .userDetailsService(userService)
                // 授权管理器
                .authenticationManager(authenticationManager)
                // 将token存储到Redis中
//                .tokenStore(tokenStore);
                // 将token存储到JWT中
                .tokenStore(tokenStore)
                .accessTokenConverter(jwtAccessTokenConverter)
                // 配置JWT内容增强器
                .tokenEnhancer(enhancerChain);
    }


    // 单点登录，配合oauth2client01demo
    // 测试方法：
    // 1.先启动springsecurityoauth2demo，再启动oauth2client01demo
    // 2.直接在浏览器访问oauth2client01demo中的接口：http://localhost:8081/user/getCurrentUser
    // 3.此时跳转到认证服务器，需要输入认证服务器的登录账号(admin)和密码(123456)
    // 4.由于开启了自动授权配置autoApprove(true)，因此认证服务器登录成功后即可直接访问到http://localhost:8081/user/getCurrentUser
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 获取秘钥需要身份认证，单点登录时必须配置
        security.tokenKeyAccess("isAuthenticated()");
    }
}
